﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using PepsiCo.Common.Entities;
using PepsiCo.Common.Services;
using T2V.SharePoint.Common.Utilities;
using PepsiCo.Common;
using System.Data;

namespace PepsiCo.Intranet.WebParts.ContactInfomation
{
    public partial class ContactInfomationUserControl : UserControl
    {
        #region [Properties]
        public ContactInfomation WebPart { get; set; }

        public int PageSize
        {
            get
            {
                int number = 10;

                if (WebPart != null)
                {
                    int.TryParse(WebPart.PageSize, out number);
                }

                return number;
            }
        }

        
        public int PictureWidth
        {
            get
            {
                int w = 150;

                if (WebPart != null)
                {
                    //w = WebPart.PictureWidth.IndexOf("px") != -1 ? WebPart.PictureWidth : WebPart.PictureWidth.Trim() + "px";
                    w = WebPart.PictureWidth;
                }

                return w;
            }
        }
        #endregion [Properties]
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            rptContactInfomation.ItemDataBound += new RepeaterItemEventHandler(rptContactInfomation_ItemDataBound);
        }

        void rptContactInfomation_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                ContactInformationItem rowView = (ContactInformationItem)e.Item.DataItem;
                if (rowView != null)
                {
                    Image imgEmployee = (Image)e.Item.FindControl("imgEmployee");
                    imgEmployee.ImageUrl = !string.IsNullOrEmpty(rowView.Thumbnail) ? rowView.Thumbnail : (SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/') + "/Style Library/Images/no_avatar.png");
                    imgEmployee.Width = PictureWidth;
                    //if (string.IsNullOrEmpty(rowView.Thumbnail)) imgEmployee.Visible = false;

                    Literal literalName = (Literal)e.Item.FindControl("literalName");
                    literalName.Text = rowView.Title;

                    Literal literalTitle = (Literal)e.Item.FindControl("literalTitle");
                    literalTitle.Text = "Title: " + rowView.JobTitle;
                    if (string.IsNullOrEmpty(rowView.JobTitle)) literalTitle.Visible = false;

                    Literal literalPhone = (Literal)e.Item.FindControl("literalPhone");
                    literalPhone.Text = "Phone: " + rowView.PhoneNumber;
                    if (string.IsNullOrEmpty(rowView.PhoneNumber)) literalPhone.Visible = false;

                    Literal literalDescription = (Literal)e.Item.FindControl("literalDescription");
                    literalDescription.Text = rowView.ShortDescription;
                    if (string.IsNullOrEmpty(rowView.ShortDescription)) literalDescription.Visible = false;
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData(1, string.Empty);
            }
        }

        private void LoadData(int currentPage, string pagingInfo)
        {
            ViewState["CICurrentPage"] = currentPage;
            FillData(pagingInfo, "Title", true);
        }

        protected void FillData(string pagingInfo, string sortColumn, bool sortAscending)
        {
            int currentPage = Convert.ToInt32(ViewState["CICurrentPage"]);
            int rowCount = PageSize;
            string columnValue;
            string nextPageString = "Paged=TRUE&p_ID={0}&p_" + sortColumn + "={1}";
            string previousPageString = "Paged=TRUE&PagedPrev=TRUE&p_ID={0}&p_" + sortColumn + "={1}";

            SPListItemCollection collection;
            SPList list = Utility.GetListFromURL(PepsiCoConstants.CONTACT_INFORMATION_LIST_URL, SPContext.Current.Web);

            List<ContactInformationItem> contacts = ContactInformationService.GetContactInformations(list, rowCount, pagingInfo, out collection);

            if (contacts != null && contacts.Count > 0)
            {
                rptContactInfomation.DataSource = contacts;
                rptContactInfomation.DataBind();

                //identify if this is a call from next or first
                if (collection != null && collection.ListItemCollectionPosition != null)
                {
                    if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[collection.Count - 1][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                    }
                    else
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToString(collection[collection.Count - 1][sortColumn]));
                    }

                    nextPageString = string.Format(nextPageString, collection[collection.Count - 1].ID, columnValue);
                }
                else
                {
                    nextPageString = string.Empty;
                }

                if (currentPage > 1)
                {

                    if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[0][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                    }
                    else
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToString(collection[0][sortColumn]));
                    }

                    previousPageString = string.Format(previousPageString, collection[0].ID, columnValue);
                }
                else
                {
                    previousPageString = string.Empty;
                }

                if (string.IsNullOrEmpty(nextPageString))
                {
                    ibtnNext.Visible = false;
                }
                else
                {
                    ibtnNext.Visible = true;
                }

                if (string.IsNullOrEmpty(previousPageString))
                {
                    ibtnPrev.Visible = false;
                }
                else
                {
                    ibtnPrev.Visible = true;
                }

                ViewState["CIPrevious"] = previousPageString;
                ViewState["CINext"] = nextPageString;
                lblPage.Text = ((currentPage - 1) * rowCount) + 1 + " - " + (currentPage * rowCount - (rowCount - contacts.Count));
            }
        }

        protected void ibtnPrev_Click(object sender, ImageClickEventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CICurrentPage"]) - 1, ViewState["CIPrevious"] as string);
        }

        protected void ibtnNext_Click(object sender, ImageClickEventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CICurrentPage"]) + 1, ViewState["CINext"] as string);
        }
    }
}
